package com.ssy.lingxi.purchase.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.manage.ShopEnvironmentEnum;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.request.ImportBatchListRequest;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.CollectionPageUtil;
import com.ssy.lingxi.common.utils.DateUtil;
import com.ssy.lingxi.component.rabbitMQ.constants.MessageConstants;
import com.ssy.lingxi.feign.UploadControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignBatchByIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignBatchByIdQueryVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLrcVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRoleVO;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.platform.manage.api.feign.inner.ShopControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.vo.shop.ShopVO;
import com.ssy.lingxi.purchase.api.common.OrderConstant;
import com.ssy.lingxi.purchase.api.common.PurchaseInquiryConstant;
import com.ssy.lingxi.purchase.api.dto.request.*;
import com.ssy.lingxi.purchase.api.dto.request.bidding.PurchaseMakeList;
import com.ssy.lingxi.purchase.api.dto.request.purchase.*;
import com.ssy.lingxi.purchase.api.dto.response.BiddingExternalWorkStateEnumResponse;
import com.ssy.lingxi.purchase.api.dto.response.CountryAreaResponse;
import com.ssy.lingxi.purchase.api.dto.response.bidding.PurchaseMakeListRequest;
import com.ssy.lingxi.purchase.api.dto.response.online.CountryArea;
import com.ssy.lingxi.purchase.api.dto.response.purchase.*;
import com.ssy.lingxi.purchase.api.enums.common.OrderTypeEnum;
import com.ssy.lingxi.purchase.api.enums.purchase.*;
import com.ssy.lingxi.purchase.config.rabbitmq.OrderRbbitMqRequest;
import com.ssy.lingxi.purchase.config.rabbitmq.provider.RabbitMQProvider;
import com.ssy.lingxi.purchase.entity.ImportBatchNo;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.*;
import com.ssy.lingxi.purchase.entity.quotedprice.QQuotedPrice;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPrice;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPriceDetails;
import com.ssy.lingxi.purchase.repository.*;
import com.ssy.lingxi.purchase.service.PurchaseInquiryService;
import com.ssy.lingxi.purchase.utils.ExcelImportUtil;
import com.ssy.lingxi.report.api.enums.ConfirmDemandQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.enums.PurchaseInquiryOperateTypeEnum;
import com.ssy.lingxi.search.api.feign.IOrderFeign;
import com.ssy.lingxi.search.api.model.request.AttributeRequest;
import com.ssy.lingxi.search.api.model.request.OrderRequest;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskStartVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 采购询价单业务处理类
 *
 * @author wrc
 * @date 2021/1/19
 */
@Slf4j
@Service
public class PurchaseInquiryServiceImpl extends BasePurchaseInquiry implements PurchaseInquiryService {

    @Resource
    PurchaseInquiryRepository purchaseInquiryRepository;
    @Resource
    PurchaseInquiryProductRepository purchaseInquiryProductRepository;

    @Resource
    InteriorPurchaseInquiryLogRepository interiorPurchaseInquiryLogRepository;

    @Resource
    ExternalPurchaseInquiryLogRepository externalPurchaseInquiryLogRepository;

    @Resource
    MemberInnerControllerFeign memberInnerControllerFeign;
    @Resource
    IOrderFeign iOrderFeign;

    @Resource
    ImportBatchNoRepository importBatchNoRepository;
    @Resource
    RabbitMQProvider rabbitMQProvider;
    @Resource
    QuotedPriceRepository quotedPriceRepository;

    @Resource
    UploadControllerFeign uploadControllerFeign;

    @Resource
    QuotedPriceDetailsRepository quotedPriceDetailsRepository;
    @Resource
    JPAQueryFactory queryFactory;
    @Resource
    PurchaseInquiryAreaRepository purchaseInquiryAreaRepository;
    @Resource
    ShopControllerFeign shopControllerFeign;
    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;

    /**
     * 采购需求单查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryList(UserLoginCacheDTO sysUser, PurchaseInquiryListRequest request) {
        return getQuery(sysUser, request, PurchaseInquiryListEnum.PURCHASE_INQUIRY_LIST.getType());
    }


    /**
     * 采购需求单详情查询
     */
    @Override
    public Wrapper<PurchaseInquiryDetailsResponse> purchaseInquiryDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiryDetailsResponse response = new PurchaseInquiryDetailsResponse();
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        } else {
            purchaseInquiry = purchaseInquiryRepository.findByPurchaseInquiryNoAndCreateMemberIdAndCreateMemberRoleId(request.getNumber(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        List<InteriorPurchaseInquiryLogResponse> interiorLog = getInteriorLog(purchaseInquiry.getId());
        response.setOffer(purchaseInquiry.getOffer());
        response.setTransactionUurls(purchaseInquiry.getTransactionUurls());
        response.setAreas(purchaseInquiry.getAreas().stream().map(v -> {
            CountryAreaResponse countryAreaResponse = new CountryAreaResponse();
            BeanUtils.copyProperties(v, countryAreaResponse);
            return countryAreaResponse;
        }).collect(Collectors.toList()));
        response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(interiorLog.get(interiorLog.size() - 1).getState()));
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        //查询采购物料
        List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<PurchaseInquiryProductRequest> productRequests = products.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        response.setMateriels(productRequests);
        //查询需求对接会员列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(purchaseInquiry.getType())) {
            response.setDemandMembers(getDemandMembers(purchaseInquiry.getId()));
        }
        response.setShopIds(purchaseInquiry.getShopIds());
        //查询内部操作记录
        response.setInteriorLogs(interiorLog);
        //查询内部流转状态
        response.setInteriorLogStates(getLogStateInterior(purchaseInquiry.getMemberId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorState()));
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalState(), roles, purchaseInquiry.getCreateMemberRoleId()));
        //组装截止时间给前端
        response.setDays(0 <= DateUtil.judgeTime(response.getOfferEndTime())[0] ? DateUtil.judgeTime(response.getOfferEndTime())[0] : 0);
        response.setHours(0 <= DateUtil.judgeTime(response.getOfferEndTime())[1] ? DateUtil.judgeTime(response.getOfferEndTime())[1] : 0);
        response.setMinutes(0 <= DateUtil.judgeTime(response.getOfferEndTime())[2] ? DateUtil.judgeTime(response.getOfferEndTime())[2] : 0);
        return Wrapper.success(response);
    }

    /**
     * 采购需求单详情查询
     */
    @Override
    public Wrapper<PurchaseInquiryDetailsResponse> details(BaseDetailsRequest request, UserLoginCacheDTO user) {
        PurchaseInquiryDetailsResponse response = new PurchaseInquiryDetailsResponse();
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        } else {
            purchaseInquiry = purchaseInquiryRepository.findByPurchaseInquiryNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setOffer(purchaseInquiry.getOffer());
        response.setTransactionUurls(purchaseInquiry.getTransactionUurls());
        response.setAreas(purchaseInquiry.getAreas().stream().map(v -> {
            CountryAreaResponse countryAreaResponse = new CountryAreaResponse();
            BeanUtils.copyProperties(v, countryAreaResponse);
            return countryAreaResponse;
        }).collect(Collectors.toList()));
        response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(purchaseInquiry.getInteriorState()));
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        //查询采购物料
        List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<PurchaseInquiryProductRequest> productRequests = products.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        response.setMateriels(productRequests);
        //查询需求对接会员列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(purchaseInquiry.getType())) {
            response.setDemandMembers(getDemandMembers(purchaseInquiry.getId()));
        }
        response.setShopIds(purchaseInquiry.getShopIds());
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalState(), roles, purchaseInquiry.getCreateMemberRoleId()));
        //组装截止时间给前端
        response.setDays(0 <= DateUtil.judgeTime(response.getOfferEndTime())[0] ? DateUtil.judgeTime(response.getOfferEndTime())[0] : 0);
        response.setHours(0 <= DateUtil.judgeTime(response.getOfferEndTime())[1] ? DateUtil.judgeTime(response.getOfferEndTime())[1] : 0);
        response.setMinutes(0 <= DateUtil.judgeTime(response.getOfferEndTime())[2] ? DateUtil.judgeTime(response.getOfferEndTime())[2] : 0);

        if (user != null) {
            //判断当前用户是否已经报过价
            if (quotedPriceRepository.existsAllByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleIdAndTurn(
                    response.getId(), user.getMemberId(), user.getMemberRoleId(), response.getTurn()
            )) {
                response.setIsRegister(CommonConstant.State.STATE_START);
            }

            //判断当前登录用户能否报价（能报价的条件为：当前会员角色类型为服务提供者并且发布询价单的会员不等于当前会员）
            if (user.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode()) &&
                    !response.getMemberId().equals(user.getMemberId())) {
                response.setCanRegister(Boolean.TRUE);
            }
        } else {
            response.setCanRegister(Boolean.TRUE);
        }
        return Wrapper.success(response);
    }

    /**
     * 添加采购询价单
     */
    @Override
    @Transactional
    public Wrapper<?> purchaseInquiryAdd(PurchaseInquiryAddRequest request, UserLoginCacheDTO sysUser) {
        long time = System.currentTimeMillis();
        //判断报价时间必须大于当前时间
        if (time >= request.getDeliveryTime()) {
            return Wrapper.fail(ResponseCode.REPORT_PRICE_TIME_NOT_CURRENT_TIME);
        }
        //判断报价截止时间必须大于当前时间
        if (request.getOfferEndTime() < time) {
            return Wrapper.fail(ResponseCode.OFFER_END_NOT_CURRENT_TIME);
        }
        //报价截止时间必须小于于交付日期
        if (request.getOfferEndTime() > request.getDeliveryTime()) {
            return Wrapper.fail(ResponseCode.OFFER_END_NOT_LOE_CURRENT_TIME);
        }

        //初始化采购询价单详情
        PurchaseInquiry purchaseInquiry = initPurchaseInquiry(request, sysUser);

        //调用会员服务 -> 根据会员ID和角色ID获取平台会员的信用积分
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(sysUser.getMemberId());
        memberFeignVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<MemberFeignLrcVO> wrapper = memberLevelRightCreditControllerFeign.getPlatformMemberLrc(memberFeignVO);
        if (wrapper.getCode() == ResponseCode.SUCCESS.getCode() && wrapper.getData() != null) {
            purchaseInquiry.setIntegral(wrapper.getData().getCreditPoint());
        } else {
            log.error("调用会员服务失败：{}", wrapper.getMessage());
        }

        //新增
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);

        if (!CollectionUtils.isEmpty(purchaseInquiry.getAreas())) {
            List<PurchaseInquiryArea> purchaseInquiryAreas = purchaseInquiry.getAreas().stream().map(temp -> {
                PurchaseInquiryArea purchaseInquiryArea = new PurchaseInquiryArea();
                BeanUtils.copyProperties(temp, purchaseInquiryArea);
                purchaseInquiryArea.setPurchaseInquiryId(purchaseInquiry.getId());
                return purchaseInquiryArea;
            }).collect(Collectors.toList());
            purchaseInquiryAreaRepository.saveAll(purchaseInquiryAreas);
        }
        //生成物料信息列表
        List<PurchaseInquiryProduct> purchaseInquiryProducts = initPurchaseInquiryProduct(request.getMateriels(), purchaseInquiry.getId());
        purchaseInquiryProductRepository.saveAll(purchaseInquiryProducts);
        //保存需求对接列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(request.getType())) {
            demandMemberRepository.saveAll(initDemandMember(request.getDemandMembers(), request.getType(), purchaseInquiry.getId()));
        }
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = startWork(sysUser, purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        purchaseInquiry.setOffer(request.getOffer());
        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.ADD.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> taskExternal = startWork(sysUser, purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskExternal.getCode()) {
            throw new RuntimeException(taskExternal.getMessage());
        }
        purchaseInquiry.setExternalTaskId(taskExternal.getData().getTaskId());
        purchaseInquiry.setExternalState(taskExternal.getData().getStatus());
        purchaseInquiry.setExternalNextStep(taskExternal.getData().getStep());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode(), 0L, 0);
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_wait_audit);
        return Wrapper.success();
    }

    /**
     * 修改需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryUpdate(PurchaseInquiryUpdateRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //判断需求单状态是否可以修改
        if (!isUpdate(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_UPDATE_BECAUSE_OF_STATUS_MISMATCH);
        }
        updateOrder(purchaseInquiry, request);
        if (!CollectionUtils.isEmpty(purchaseInquiry.getAreas())) {
            purchaseInquiryAreaRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
            List<PurchaseInquiryArea> purchaseInquiryAreas = purchaseInquiry.getAreas().stream().map(temp -> {
                PurchaseInquiryArea purchaseInquiryArea = new PurchaseInquiryArea();
                BeanUtils.copyProperties(temp, purchaseInquiryArea);
                purchaseInquiryArea.setPurchaseInquiryId(purchaseInquiry.getId());
                return purchaseInquiryArea;
            }).collect(Collectors.toList());
            purchaseInquiryAreaRepository.saveAll(purchaseInquiryAreas);
        }
        //保存需求对接列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(request.getType())) {
            demandMemberRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
            demandMemberRepository.flush();
            demandMemberRepository.saveAll(initDemandMember(request.getDemandMembers(), request.getType(), purchaseInquiry.getId()));
        }
        //生成物料信息列表
        List<PurchaseInquiryProduct> purchaseInquiryProducts = initPurchaseInquiryProduct(request.getMateriels(), purchaseInquiry.getId());
        purchaseInquiryProductRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
        purchaseInquiryProductRepository.flush();
        purchaseInquiryProductRepository.saveAll(purchaseInquiryProducts);
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = startWork(sysUser, purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.UPDATE.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> taskExternal = startWork(sysUser, purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskExternal.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        purchaseInquiry.setExternalTaskId(taskExternal.getData().getTaskId());
        purchaseInquiry.setExternalState(taskExternal.getData().getStatus());
        purchaseInquiry.setExternalNextStep(taskExternal.getData().getStep());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        return Wrapper.success();
    }

    /**
     * 删除需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryDelete(BaseRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (isDelete(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_DELETE);
        }
        purchaseInquiryProductRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
        demandMemberRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
        purchaseInquiryRepository.deleteById(purchaseInquiry.getId());
        interiorPurchaseInquiryLogRepository.deleteAllByPurchaseInquiryId(purchaseInquiry.getId());
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 0L, 0, 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode());
        return Wrapper.success();
    }

    /**
     * 批量删除需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryDeleteBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllByCreateMemberIdAndCreateMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (isDelete(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_DELETE);
            }
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 0L, 0, 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode());
        }
        purchaseInquiryProductRepository.deleteAllByPurchaseInquiryIdIn(request.getIds());
        demandMemberRepository.deleteAllByPurchaseInquiryIdIn(request.getIds());
        interiorPurchaseInquiryLogRepository.deleteAllByPurchaseInquiryIdIn(request.getIds());
        purchaseInquiryRepository.deleteAllByIdIn(request.getIds());
        return Wrapper.success();
    }

    /**
     * 待新增采购需求单
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryAddList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        //发布商城类型为采购门户
        request.setShopType(ShopTypeEnum.PURCHASE.getCode());
        Wrapper<PageData<PurchaseInquiryListResponse>> query = getQuery(sysUser, request, PurchaseInquiryListEnum.ADD_PURCHASE_INQUIRY_LIST.getType());
        if (ResponseCode.SUCCESS.getCode() == query.getCode() && !CollectionUtils.isEmpty(query.getData().getData())) {
            query.getData().getData().forEach(response -> {
                response.setButton(PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(response.getInteriorState()) ? ButtonEnum.SUBMIT_ORDER.getStep() : ButtonEnum.CONFIRM_ORDER.getStep());
            });
        }
        return query;
    }

    /**
     * 提交审核采购需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamine(BaseRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(purchaseInquiry.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT_EXAMINE.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode());
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit_step_1);
        return Wrapper.success();
    }

    /**
     * 提交审核采购需求单批量
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamineBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllByCreateMemberIdAndCreateMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(purchaseInquiry.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
            purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
            purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT_EXAMINE.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit_step_1);
        }
        purchaseInquiryRepository.saveAll(purchaseInquirys);
        purchaseInquiryRepository.flush();
        return Wrapper.success();
    }

    /**
     * 采购询价-待审核采购需求单(一级)
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryStayExamineList1(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getQuery(sysUser, request, PurchaseInquiryListEnum.EXAMINE_PURCHASE_INQUIRY_LIST1.getType());
    }

    /**
     * 采购询价-审核采购需求单(一级)
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamine1(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE1.getState().equals(purchaseInquiry.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
        }
        boolean isPass = OrderConstant.State.START.equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }

        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.EXAMINE1.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), isPass ? StatusEnum.AGREE.getCHName() : request.getAuditOpinion());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        if (isPass) {
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit_step_2);
        } else {
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_wait_audit);
        }
        return Wrapper.success();
    }

    /**
     * 审核采购需求单(一级)批量
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamine1Batch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllByCreateMemberIdAndCreateMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE1.getState().equals(purchaseInquiry.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
            purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
            purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT_EXAMINE1.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit_step_2);
        }
        purchaseInquiryRepository.saveAll(purchaseInquirys);
        purchaseInquiryRepository.flush();
        return Wrapper.success();
    }

    /**
     * 采购询价-待审核采购需求单(二级)
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryStayExamineList2(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getQuery(sysUser, request, PurchaseInquiryListEnum.EXAMINE_PURCHASE_INQUIRY_LIST2.getType());
    }

    /**
     * 采购询价-审核采购需求单(二级)
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamine2(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE2.getState().equals(purchaseInquiry.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
        }
        boolean isPass = OrderConstant.State.START.equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }

        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.EXAMINE2.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), isPass ? StatusEnum.AGREE.getCHName() : request.getAuditOpinion());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        if (isPass) {
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_submit);
        } else {
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_VALIFY_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_wait_audit);
        }
        return Wrapper.success();
    }

    /**
     * 审核采购需求单(二级)批量
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryExamine2Batch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllByCreateMemberIdAndCreateMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE2.getState().equals(purchaseInquiry.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
            purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
            purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT_EXAMINE2.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_COUNT.getCode(), 1L, PurchaseInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_submit);
        }
        purchaseInquiryRepository.saveAll(purchaseInquirys);
        purchaseInquiryRepository.flush();
        return Wrapper.success();
    }

    /**
     * 待提交采购需求单
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryStayCommitList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getQuery(sysUser, request, PurchaseInquiryListEnum.SUBMIT_PURCHASE_INQUIRY_LIST.getType());
    }

    /**
     * 提交采购需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryCommit(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT_OFFER.getState().equals(purchaseInquiry.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), StatusEnum.AGREE.getCHName());
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> externalResult = executeWork(purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != externalResult.getCode()) {
            return externalResult;
        }
        purchaseInquiry.setExternalTaskId(externalResult.getData().getTaskId());
        purchaseInquiry.setExternalState(externalResult.getData().getStatus());
        purchaseInquiry.setExternalNextStep(externalResult.getData().getStep());
        saveExternalLog(sysUser, PurchaseInquiryExternalOperationRecordEnum.SUBMIT_PURCHASE_ORDER.getCHName(), externalResult.getData().getStatus(), purchaseInquiry.getId(), "");
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        //发送mq消息
        OrderRbbitMqRequest rabbitMqRequest = new OrderRbbitMqRequest();
        rabbitMqRequest.setId(purchaseInquiry.getId());
        rabbitMqRequest.setMemberId(purchaseInquiry.getCreateMemberId());
        rabbitMqRequest.setMemberRoleId(purchaseInquiry.getCreateMemberRoleId());
        rabbitMqRequest.setExpirationTime(purchaseInquiry.getOfferEndTime());
        rabbitMQProvider.sendDelayMessage(rabbitMqRequest, MessageConstants.PURCHASE_INQUIRY_DELAY_EXCHANGE, MessageConstants.PURCHASE_INQUIRY_DELAY_KEY, 2L);
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 0L, 0, 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_COUNT.getCode());
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit);
        return Wrapper.success();
    }

    /**
     * 采购询价-提交采购需求单批量
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryCommitBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllByCreateMemberIdAndCreateMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT_OFFER.getState().equals(purchaseInquiry.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep(), purchaseInquiry.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            purchaseInquiry.setInteriorTaskId(taskResult.getData().getTaskId());
            purchaseInquiry.setInteriorState(taskResult.getData().getStatus());
            purchaseInquiry.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, PurchaseInquiryInternalOperationRecordEnum.SUBMIT.getCHName(), taskResult.getData().getStatus(), taskResult.getData().getStatus(), purchaseInquiry.getId(), StatusEnum.AGREE.getCHName());
            //执行外部工作流
            Wrapper<SimpleTaskCompleteVO> externalResult = executeWork(purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.DEFAULT);
            if (ResponseCode.SUCCESS.getCode() != externalResult.getCode()) {
                return externalResult;
            }
            purchaseInquiry.setExternalTaskId(externalResult.getData().getTaskId());
            purchaseInquiry.setExternalState(externalResult.getData().getStatus());
            purchaseInquiry.setExternalNextStep(externalResult.getData().getStep());
            saveExternalLog(sysUser, PurchaseInquiryExternalOperationRecordEnum.SUBMIT_PURCHASE_ORDER.getCHName(), externalResult.getData().getStatus(), purchaseInquiry.getId(), "");
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_INQUIRY.getCode(), 0L, 0, 1L, PurchaseInquiryOperateTypeEnum.TO_BE_COMMIT_COUNT.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_publish_audit);
            //发送mq消息
            OrderRbbitMqRequest rbbitMqRequest = new OrderRbbitMqRequest();
            rbbitMqRequest.setId(purchaseInquiry.getId());
            rbbitMqRequest.setMemberId(purchaseInquiry.getCreateMemberId());
            rbbitMqRequest.setMemberRoleId(purchaseInquiry.getCreateMemberRoleId());
            rbbitMqRequest.setExpirationTime(purchaseInquiry.getOfferEndTime());
            rabbitMQProvider.sendDelayMessage(rbbitMqRequest, MessageConstants.PURCHASE_INQUIRY_DELAY_EXCHANGE, MessageConstants.PURCHASE_INQUIRY_DELAY_KEY, 2L);
        }
        purchaseInquiryRepository.saveAll(purchaseInquirys);
        purchaseInquiryRepository.flush();
        return Wrapper.success();
    }

    /**
     * 采购询价-需求对接-系统匹配会员信息列表
     */
    @Override
    public Wrapper<PageData<DemandMemberResponse>> systemMatchingMemberKInitializeList(MatchingMemberKInitializeListRequest request, UserLoginCacheDTO sysUser) {
        OrderRequest orderRequest = new OrderRequest();
        if (!CollectionUtils.isEmpty(request.getAreaRequestList())) {
            List<com.ssy.lingxi.search.api.model.request.AreaRequest> collect = request.getAreaRequestList().stream().map(temp -> {
                com.ssy.lingxi.search.api.model.request.AreaRequest areaRequest = new com.ssy.lingxi.search.api.model.request.AreaRequest();
                BeanUtils.copyProperties(temp, areaRequest);
                return areaRequest;
            }).collect(Collectors.toList());
            orderRequest.setAreaRequestList(collect);
        }
        if (!CollectionUtils.isEmpty(request.getAttributeList())) {
            List<AttributeRequest> attributeRequests = request.getAttributeList().stream().map(temp -> {
                AttributeRequest areaRequest = new AttributeRequest();
                BeanUtils.copyProperties(temp, areaRequest);
                return areaRequest;
            }).collect(Collectors.toList());
            orderRequest.setAttributeList(attributeRequests);
        }
        orderRequest.setCategoryIdList(request.getCategoryIds());
        //根据报价单查询用户信息
        Wrapper<List<Long>> memberIdList = iOrderFeign.getMemberIdList(orderRequest);
        if (ResponseCode.SUCCESS.getCode() != memberIdList.getCode()) {
            return Wrapper.fail(memberIdList.getMessage());
        }
        List<DemandMemberResponse> responses = new ArrayList<>();
        List<Long> data = memberIdList.getData();
        if (CollectionUtils.isEmpty(data)) {
            return Wrapper.success(new PageData<>(0L, responses));
        }
        Long count = (long) data.size();
        List<Long> longs = CollectionPageUtil.pageList(data, request.getCurrent(), request.getPageSize());
        MemberFeignBatchByIdVO memberFeignBatchByIdQueryVO = new MemberFeignBatchByIdVO();
        memberFeignBatchByIdQueryVO.setMemberId(sysUser.getMemberId());
        memberFeignBatchByIdQueryVO.setMemberIds(longs);
        Wrapper<List<MemberFeignBatchByIdQueryVO>> listWrapper = memberInnerControllerFeign.batchFindMembersByIdList(memberFeignBatchByIdQueryVO);
        if (listWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(listWrapper.getMessage());
        }
        responses = listWrapper.getData().stream().map(temp -> {
            DemandMemberResponse response = new DemandMemberResponse();
            response.setType(CommonConstant.State.STATE_START);
            BeanUtils.copyProperties(temp, response);
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(count, responses));
    }

    /**
     * 采购询价-需求对接-系统匹配会员信息列表查询
     */
    @Override
    public Wrapper<PageData<DemandMemberResponse>> systemMatchingMemberList(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        DemandMember member = new DemandMember();
        member.setPurchaseInquiryId(request.getId());
        Page<DemandMember> demandMemberPage = demandMemberRepository.findAll(Example.of(member), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (demandMemberPage.getTotalElements() == 0) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<DemandMember> demandMembers = demandMemberPage.getContent();
        List<DemandMemberResponse> collect = demandMembers.stream().map(temp -> {
            DemandMemberResponse response = new DemandMemberResponse();
            BeanUtils.copyProperties(temp, response);
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(demandMemberPage.getTotalElements(), collect));
    }

    /**
     * 采购询价-采购物料-分页查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryProductRequest>> purchaseInquiryProductlist(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        PurchaseInquiryProduct product = new PurchaseInquiryProduct();
        product.setPurchaseInquiryId(purchaseInquiry.getId());
        //查询采购物料
        Page<PurchaseInquiryProduct> purchaseInquiryProducts = purchaseInquiryProductRepository.findAll(Example.of(product), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (purchaseInquiryProducts.getTotalElements() == 0) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<PurchaseInquiryProductRequest> productRequests = purchaseInquiryProducts.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(purchaseInquiryProducts.getTotalElements(), productRequests));
    }

    /**
     * 查询导入批次号列表
     */
    @Override
    public Wrapper<List<ImportBatchNo>> importBatchList(ImportBatchListRequest request) {
        ImportBatchNo importBatchNo = new ImportBatchNo();
        Example<ImportBatchNo> example = Example.of(importBatchNo);
        Sort.Order order = Sort.Order.desc("batchNo");
        Sort sort = Sort.by(order);
        List<ImportBatchNo> all = importBatchNoRepository.findAll(example, sort);
        return Wrapper.success(all);
    }

    /**
     * 采购需求单导入
     */
    @Override
    public Wrapper<List<PurchaseInquiryExcelRequest>> importExcel(MultipartFile file) {
        List<PurchaseInquiryExcelRequest> list;
        try {
            list = new ExcelImportUtil<PurchaseInquiryExcelRequest>(PurchaseInquiryExcelRequest.class).readExcel(file.getInputStream(), 1, 0);
        } catch (IOException e) {
            log.error("excel解析异常", e);
            return Wrapper.fail(ResponseCode.EXCEL_UPLOAD_ERROR);
        }
        return Wrapper.success(list);
    }


    /**
     * 采购需求单导入检查
     */
    @Override
    public Wrapper<String> importExcelCheck(MultipartFile file) {
        List<PurchaseInquiryExcelRequest> list;
        try {
            list = new ExcelImportUtil<PurchaseInquiryExcelRequest>(PurchaseInquiryExcelRequest.class).readExcel(file.getInputStream(), 1, 0);
        } catch (IOException e) {
            log.error("excel解析异常", e);
            return Wrapper.fail(ResponseCode.EXCEL_UPLOAD_ERROR);
        }
        if (CollectionUtils.isEmpty(list)) {
            return Wrapper.fail(ResponseCode.EXCEL_UPLOAD_ERROR_NULL);
        }
        String errorUrl = checkField(list);
        return Wrapper.success(errorUrl);
    }

    /**
     * excel字段校验
     */
    private String checkField(List<PurchaseInquiryExcelRequest> list) {
        int size = list.size();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            if (!StringUtils.hasLength(list.get(i).getNumber())) {
                sb.append("第").append(i).append("行物料编号为空\r\n");
            }
            if (!StringUtils.hasLength(list.get(i).getName())) {
                sb.append("第").append(i).append("货品名称为空\r\n");
            }
            if (!StringUtils.hasLength(list.get(i).getBrand())) {
                sb.append("第").append(i).append("品牌为空\r\n");
            }
            if (!StringUtils.hasLength(list.get(i).getCategory())) {
                sb.append("第").append(i).append("分类为空\r\n");
            }
            if (!StringUtils.hasLength(list.get(i).getModel())) {
                sb.append("第").append(i).append("规格型号为空\r\n");
            }
            if (ObjectUtils.isEmpty(list.get(i).getPurchaseCount())) {
                sb.append("第").append(i).append("采购数量为空\r\n");
            }
            if (!StringUtils.hasLength(list.get(i).getUnit())) {
                sb.append("第").append(i).append("单位为空\r\n");
            }
        }
        Set<String> collect = list.stream().map(PurchaseInquiryExcelRequest::getNumber).collect(Collectors.toSet());
        if (size != collect.size()) {
            sb.append("物料编号重复请检查数据");
        }
        if (StringUtils.hasLength(sb.toString())) {
            return writeErorToTxt(sb.toString());
        }
        return null;
    }

    /**
     * 将错误信息输入到txt中
     */
    public String writeErorToTxt(String content) {
        File file = null;
        try {
            file = File.createTempFile("错误日记", ".txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        getFile(content, file);
        MultipartFile multipartFile = getMulFileByFile(file);
        //上传到云服务器
        Wrapper<String> upload = uploadControllerFeign.upload(multipartFile);
        file.deleteOnExit();
        return upload.getData();
    }

    /**
     * 批量执行报价截止时间到期的需求单外部流程-内部接口
     */
    @Transactional
    @Override
    public void examineQuotedPriceBatch(ExamineQuotedPriceBatchRequest request) {
        //获取所有需求单
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndExternalState(request.getId(), PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState());
        if (ObjectUtils.isEmpty(purchaseInquiry) || purchaseInquiry.getOfferEndTime() > System.currentTimeMillis()) {
            log.error("采购询价单据不存在或截止时间未到");
            return;
        }
        List<QuotedPrice> quotedPrice = quotedPriceRepository.findAllByPurchaseInquiryId(request.getId());
        List<QuotedPrice> newQuotedPrice = new ArrayList<>();
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> externalResult = executeWork(purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != externalResult.getCode()) {
            log.error("执行外部工作流失败:{}", externalResult.getMessage());
            return;
        }
        //执行内部工作流 确认报价内部
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setMemberId(purchaseInquiry.getCreateMemberId());
        processStartVO.setRoleId(purchaseInquiry.getCreateMemberRoleId());
        processStartVO.setProcessKey(ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getProcessKey());
        processStartVO.setDataId(purchaseInquiry.getId());
        Wrapper<SimpleTaskCompleteVO> taskResult = taskExecuteControllerFeign.startSimpleProcess(processStartVO);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        purchaseInquiry.setConfirmInteriorTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setConfirmInteriorState(taskResult.getData().getStatus());
        purchaseInquiry.setConfirmInteriorNextStep(taskResult.getData().getStatus());
        purchaseInquiry.setExternalTaskId(externalResult.getData().getTaskId());
        purchaseInquiry.setExternalState(externalResult.getData().getStatus());
        purchaseInquiry.setExternalNextStep(externalResult.getData().getStep());
        if (!CollectionUtils.isEmpty(quotedPrice)) {
            Map<Long, List<QuotedPrice>> collect = quotedPrice.stream().collect(Collectors.groupingBy(QuotedPrice::getPurchaseInquiryId));
            List<QuotedPrice> quotedPrices = collect.get(purchaseInquiry.getId());
            quotedPrices.forEach(details -> {
                details.setOfferEndTime(purchaseInquiry.getOfferEndTime());
                details.setExternalTaskId(externalResult.getData().getTaskId());
                details.setExternalState(externalResult.getData().getStatus());
                details.setExternalNextStep(externalResult.getData().getStep());
            });
            newQuotedPrice.addAll(quotedPrices);

            //需求单被报价的时候才会有'提交报价单'外部记录操作
            Wrapper<List<MemberFeignRoleVO>> rolesWrapper = memberInnerControllerFeign.getRoles(Stream.of(quotedPrice.get(0).getCreateMemberRoleId()).collect(Collectors.toList()));
            if (ResponseCode.SUCCESS.getCode() == rolesWrapper.getCode() && CollectionUtil.isNotEmpty(rolesWrapper.getData())) {
                UserLoginCacheDTO sysUser = new UserLoginCacheDTO();
                sysUser.setMemberId(quotedPrice.get(0).getCreateMemberId());
                sysUser.setMemberRoleId(quotedPrice.get(0).getCreateMemberRoleId());
                sysUser.setMemberRoleName(rolesWrapper.getData().get(0).getRoleName());
                saveExternalLog(sysUser, PurchaseInquiryExternalOperationRecordEnum.SUBMIT_QUOTATION.getCHName(), externalResult.getData().getStatus(), purchaseInquiry.getId(), "");
                //保存待比价日志信息
                saveInteriorConfirmQuotedPriceLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getName(), PurchaseInquiryListInteriorWorkStateEnum.CONTRAST_PRICE.getState(), PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState(), purchaseInquiry.getId(), "");
            }
        }

        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_wait_audit);
        reduceCount(quotedPrice.get(0).getDetails(), quotedPrice.get(0).getMemberId(), quotedPrice.get(0).getMemberRoleId(), OperateDataSourceEnum.PURCHASE_CONFIRM_QUOTED_PRICE.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        quotedPriceRepository.saveAll(newQuotedPrice);
        quotedPriceRepository.flush();
        purchaseInquiryRepository.save(purchaseInquiry);
        purchaseInquiryRepository.flush();
        log.info("执行采购确认报价成功");
    }

    /**
     * 作废需求单
     */
    @Transactional
    @Override
    public Wrapper purchaseInquiryCancel(PurchaseInquiryCancelRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //已作废状态不能作废
        if (PurchaseInquiryListExternalWorkStateEnum.CANCEL.getState().equals(purchaseInquiry.getExternalState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_INQUIRY_PRICE_DO_NOT_REPEAT);
        }
        //已完成状态不能作废
        if (PurchaseInquiryListExternalWorkStateEnum.COMPLETE.getState().equals(purchaseInquiry.getExternalState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_INQUIRY_PRICE_STATUS_IS_COMPLETE);
        }
        purchaseInquiry.setInteriorState(OrderConstant.Auditing.DEFAULT);
        purchaseInquiry.setNullifyTime(request.getReasonTime());
        purchaseInquiry.setExternalState(OrderConstant.Auditing.DEFAULT);
        saveExternalLog(sysUser, PurchaseInquiryExternalOperationRecordEnum.TO_VOID.getCHName(), OrderConstant.Auditing.DEFAULT, purchaseInquiry.getId(), request.getReason());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        return Wrapper.success();
    }

    /**
     * 需求单详情-获取已经报价的物料详情列表分页查询
     */
    @Override
    public Wrapper<PageData<QuotedPriceProductResponse>> getMaterielsByPurchaseInquiryId(MaterielsByPurchaseInquiryIdRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPriceProductResponse> lsit = new ArrayList<>();
        QuotedPrice quotedPrice = quotedPriceRepository.findByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.success(new PageData<>(0L, lsit));
        }
        Page<QuotedPriceDetails> page = quotedPriceDetailsRepository.findAllByQuotedPriceIdAndTurn(quotedPrice.getId(), request.getTurn(), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (page.getTotalElements() > 0) {
            lsit = page.getContent().stream().map(temp -> {
                QuotedPriceProductResponse response = new QuotedPriceProductResponse();
                BeanUtils.copyProperties(temp, response);
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(page.getTotalElements(), lsit));
    }

    /**
     * 采购商机筛选-采购询价列表-需求对接为发布至平台且发布的商城为企业商城且商城环境为WEB的采购需求单
     */
    @Override
    public Wrapper<PageData<PurchaseListResponse>> platformPurchaseList(PurchaseListRequest request) {
        //查询商城为企业商城且商城环境为WEB的shopID
        long shopId = 1L;
        Wrapper<List<ShopVO>> listWrapper = shopControllerFeign.findAllByShopTypeAndEnvironment(ShopTypeEnum.ENTERPRISE.getCode(), ShopEnvironmentEnum.WEB.getCode());
        if (ResponseCode.SUCCESS.getCode() == listWrapper.getCode() && !CollectionUtils.isEmpty(listWrapper.getData())) {
            shopId = listWrapper.getData().get(0).getId();
        }
        Wrapper<PageData<PurchaseListResponse>> pageDataWrapper = queryList(request, shopId);
        if (ResponseCode.SUCCESS.getCode() != pageDataWrapper.getCode() || CollectionUtils.isEmpty(pageDataWrapper.getData().getData())) {
            return pageDataWrapper;
        }
        //聚合统计单据的物料总数、分类
        List<PurchaseListResponse> data = pageDataWrapper.getData().getData();
        //筛选shopId包含web企业商城的
        final long finalShopId = shopId;
        data = data.stream().filter(purchase -> !CollectionUtils.isEmpty(purchase.getShopIds()) && purchase.getShopIds().contains(finalShopId)).collect(Collectors.toList());
        Map<Long, List<PurchaseListResponse>> collect = data.stream().collect(Collectors.groupingBy(PurchaseListResponse::getId));
        List<PurchaseListResponse> purchaseList = new ArrayList<>();
        for (Long id : collect.keySet()) {
            List<PurchaseListResponse> purchaseListResponses = collect.get(id);
            PurchaseListResponse purchaseListResponse = purchaseListResponses.get(0);
            //获得物料总和
            int size = purchaseListResponses.stream().map(PurchaseListResponse::getProductId).collect(Collectors.toSet()).size();
            purchaseListResponse.setCount(size);
            //获得分类集合
            Set<String> ids = purchaseListResponses.stream().map(PurchaseListResponse::getCategory).collect(Collectors.toSet());
            if (!CollectionUtils.isEmpty(ids)) {
                purchaseListResponse.setCategory(StringUtils.collectionToDelimitedString(ids, "、"));
            }
            if (!ObjectUtils.isEmpty(purchaseListResponse)) {
                purchaseListResponse.setCreateTimeStr(DateUtil.timeStamp2Date(purchaseListResponse.getCreateTime(), "yyyy-MM-dd HH:mm"));
                purchaseListResponse.setDeliveryTimeStr(DateUtil.timeStamp2Date(purchaseListResponse.getDeliveryTime(), "yyyy-MM-dd HH:mm"));
                purchaseListResponse.setDays(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[0] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[0] : 0);
                purchaseListResponse.setHours(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[1] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[1] : 0);
                purchaseListResponse.setMinutes(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[2] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[2] : 0);

            }
            purchaseList.add(purchaseListResponse);
        }
        //分页
        List<PurchaseListResponse> purchaseListResponses = CollectionPageUtil.pageList(purchaseList, request.getCurrent() + 1, request.getPageSize());
        pageDataWrapper.getData().setData(purchaseListResponses);
        return Wrapper.success(new PageData<>((long) purchaseList.size(), purchaseListResponses));
    }

    /**
     * 采购公示
     */
    @Override
    public Wrapper<PageData<PurchaseMakeList>> purchaseMakeList(PurchaseMakeListRequest request) {
        List<PurchaseMakeList> responses;
        QPurchaseInquiry qBidding = QPurchaseInquiry.purchaseInquiry;
        QQuotedPrice onLineBidding = QQuotedPrice.quotedPrice;
        // 定于获取条件
        BooleanBuilder predicates = new BooleanBuilder();
        if (StringUtils.hasLength(request.getDetails())) {
            predicates.and(qBidding.details.like("%" + request.getDetails() + "%"));
        }
        if (null != request.getMemberId() && null != request.getMemberRoleId()) {
            predicates.and(onLineBidding.createMemberId.eq(request.getMemberId()));
            predicates.and(onLineBidding.createMemberRoleId.eq(request.getMemberRoleId()));
        }
        predicates.and(qBidding.notice.eq(PurchaseInquiryConstant.State.START));
        JPAQuery<PurchaseMakeList> query = queryFactory.select(Projections.bean(PurchaseMakeList.class,
                qBidding.id,
                qBidding.awardResults.as("context"),
                qBidding.details.as("pojoName"),
                qBidding.createMemberName.as("enterpriseName"),
                qBidding.updateTime.as("releaseTime")
        )).from(qBidding)
                .leftJoin(onLineBidding)
                .on(qBidding.id.eq(onLineBidding.purchaseInquiryId))
                .where(predicates);
        long totalCount = query.fetchCount();
        responses = query.orderBy(qBidding.updateTime.desc())
                .offset((request.getCurrent() - 1) * request.getPageSize())
                .limit(request.getPageSize())
                .fetch();
        if (!CollectionUtils.isEmpty(responses)) {
            responses.forEach(temp -> {
                temp.setReleaseTimeStr(DateUtil.timeStamp2Date(temp.getReleaseTime(), "yyyy-MM-dd HH:mm"));
            });
        }
        return Wrapper.success(new PageData<>(totalCount, responses));
    }

    /**
     * 采购询价：
     * 取采购能力
     * 采购询价模块中当前采购会员的采购需求单
     * 且外部状态为平台审核通过
     * 且需求对接为发布至平台门户
     * 且发布的商城为采购门户或者企业商城
     * 且商城环境为WEB的采购需求单
     * 显示需求单摘要、交付日期、交付地址、发布时间、报价剩余时间、已有报价数（统计当前需求单已收到的报价数），按发布时间倒序显示UI设计时允许显示的采购询价单，展开显示采购物料，显示物料编号、物料名称、规格型号、品类、品牌、采购数量，最多显示条数根据UI设定，可收缩不显示采购物料
     */
    @Override
    public Wrapper<PageData<SearchReSourceListResponse>> searchReSourceList(PurchaseShopListRequest request, UserLoginCacheDTO user, Long shopId) {
        List<SearchReSourceListResponse> responses;
        QPurchaseInquiry qPurchaseInquiry = QPurchaseInquiry.purchaseInquiry;
        QPurchaseInquiryArea qPurchaseInquiryArea = QPurchaseInquiryArea.purchaseInquiryArea;
        QPurchaseInquiryProduct qPurchaseInquiryProduct = QPurchaseInquiryProduct.purchaseInquiryProduct;
        // 定于获取条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(qPurchaseInquiry.externalState.notIn(PurchaseInquiryListExternalWorkStateEnum.CANCEL.getState(), PurchaseInquiryListExternalWorkStateEnum.AUDIT_NOT_REQUIREMENTS.getState(), PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_REQUIREMENTS.getState()));
        predicates.and(qPurchaseInquiry.type.eq(PurchaseInquiryConstant.type.PLATFORM));
        //若有会员在采购能力-采购门户 创建了相关记录，在传来该会员id信息时，返回该会员发布的采购需求
        if (request.getMemberId() != null) {
            predicates.and(qPurchaseInquiry.createMemberId.eq(request.getMemberId()));
        }
        if (request.getMemberRoleId() != null) {
            predicates.and(qPurchaseInquiry.createMemberRoleId.eq(request.getMemberRoleId()));
        }
        if (StringUtils.hasLength(request.getKeyword())) {
            predicates.and(qPurchaseInquiry.details.like("%" + request.getKeyword() + "%").or(qPurchaseInquiryProduct.category.like("%" + request.getKeyword() + "%")));
        }
        if (null != request.getStartTime()) {
            predicates.and(qPurchaseInquiry.createTime.goe(request.getStartTime()));
        }
        if (null != request.getEndTime()) {
            predicates.and(qPurchaseInquiry.createTime.loe(request.getEndTime()));
        }
        if (OrderConstant.State.START.equals(request.getOverdue())) {
            predicates.and(qPurchaseInquiry.offerEndTime.goe(System.currentTimeMillis()));
        }
        //貌似没用上
        if (!ObjectUtils.isEmpty(request.getArea())) {
            if (StringUtils.hasLength(request.getArea().getAreaCode())) {
                predicates.and(qPurchaseInquiryArea.areaCode.eq(request.getArea().getAreaCode()));
            }
            if (StringUtils.hasLength(request.getArea().getCityCode())) {
                predicates.and(qPurchaseInquiryArea.cityCode.eq(request.getArea().getCityCode()));
            }
            if (StringUtils.hasLength(request.getArea().getProvinceCode())) {
                predicates.and(qPurchaseInquiryArea.provinceCode.eq(request.getArea().getProvinceCode()));
            }
        }
        if (request.getCategory() != null) {
            predicates.and(qPurchaseInquiryProduct.categoryId.eq(request.getCategory()));
        }
        if (request.getMemberCategory() != null) {
            predicates.and(qPurchaseInquiryProduct.memberCategoryId.eq(request.getMemberCategory()));
        }
        if (StringUtils.hasLength(request.getCityCode())) {
            predicates.and(qPurchaseInquiryArea.cityCode.eq(request.getCityCode()).or((qPurchaseInquiryArea.cityCode).eq("0")).or((qPurchaseInquiryArea.cityCode).eq("")));
        }
        if (StringUtils.hasLength(request.getProvinceCode())) {
            predicates.and(qPurchaseInquiryArea.provinceCode.eq(request.getProvinceCode()).or((qPurchaseInquiryArea.provinceCode).eq("0")).or((qPurchaseInquiryArea.provinceCode).eq("")));
        }
        JPAQuery<SearchReSourceListResponse> query = queryFactory.select(Projections.bean(SearchReSourceListResponse.class,
                qPurchaseInquiry.integral.as("memberIntegral"),
                qPurchaseInquiry.turn,
                qPurchaseInquiry.count.as("quoteCount"),
                qPurchaseInquiry.id,
                qPurchaseInquiry.purchaseInquiryNo,
                qPurchaseInquiry.details,
                qPurchaseInquiry.createTime,
                qPurchaseInquiry.shopIds,
                qPurchaseInquiry.areas,
                qPurchaseInquiry.deliveryTime,
                qPurchaseInquiry.offerEndTime,
                qPurchaseInquiry.address,
                qPurchaseInquiry.addressId,
                qPurchaseInquiryProduct.id.as("productId"),
                qPurchaseInquiryProduct.category,
                qPurchaseInquiryProduct.ids,
                qPurchaseInquiry.createMemberId.as("memberId"),
                qPurchaseInquiry.createMemberName.as("memberName"),
                qPurchaseInquiry.createMemberRoleId.as("memberRoleId")
        )).from(qPurchaseInquiry)
                .leftJoin(qPurchaseInquiryProduct)
                .on(qPurchaseInquiry.id.eq(qPurchaseInquiryProduct.purchaseInquiryId))
                .leftJoin(qPurchaseInquiryArea)
                .on(qPurchaseInquiry.id.eq(qPurchaseInquiryArea.purchaseInquiryId))
                .where(predicates);
        responses = query.orderBy(qPurchaseInquiry.createTime.desc())
                .fetch();

//        if (StringUtils.hasLength(request.getCategory())) {
//            responses = responses.stream().filter(a -> a.getIds().contains(request.getCategory())).collect(Collectors.toList());
//        }

        //筛选shopId包含web企业商城 聚合统计单据的物料总数、分类
        responses = responses.stream().filter(purchase -> !CollectionUtils.isEmpty(purchase.getShopIds()) && purchase.getShopIds().contains(shopId)).collect(Collectors.toList());
        Map<Long, List<SearchReSourceListResponse>> collect = responses.stream().collect(Collectors.groupingBy(SearchReSourceListResponse::getId));
        long totalCount = collect.size();
        List<SearchReSourceListResponse> purchaseList = new ArrayList<>();
        for (Long id : collect.keySet()) {
            List<SearchReSourceListResponse> purchaseListResponses = collect.get(id);
            SearchReSourceListResponse purchaseListResponse = purchaseListResponses.get(0);
            //获得物料总和
            int size = purchaseListResponses.stream().map(SearchReSourceListResponse::getProductId).collect(Collectors.toSet()).size();
            purchaseListResponse.setCount(size);
            //获得分类集合
            Set<String> ids = purchaseListResponses.stream().map(SearchReSourceListResponse::getCategory).collect(Collectors.toSet());
            if (!CollectionUtils.isEmpty(ids)) {
                purchaseListResponse.setCategory(StringUtils.collectionToDelimitedString(ids, "、"));
            }
            if (!ObjectUtils.isEmpty(purchaseListResponse)) {
                purchaseListResponse.setCreateTimeStr(DateUtil.timeStamp2Date(purchaseListResponse.getCreateTime(), "yyyy-MM-dd HH:mm"));
                purchaseListResponse.setDeliveryTimeStr(DateUtil.timeStamp2Date(purchaseListResponse.getDeliveryTime(), "yyyy-MM-dd HH:mm"));
                purchaseListResponse.setDays(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[0] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[0] : 0);
                purchaseListResponse.setHours(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[1] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[1] : 0);
                purchaseListResponse.setMinutes(0 <= DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[2] ? DateUtil.judgeTime(purchaseListResponse.getOfferEndTime())[2] : 0);
            }
            purchaseList.add(purchaseListResponse);
        }
        //分页
        if (!CollectionUtils.isEmpty(responses)) {
            //查询详情
            List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryIdIn(responses.stream().map(SearchReSourceListResponse::getId).collect(Collectors.toSet()));
            if (!CollectionUtils.isEmpty(products)) {
                List<SearchReSourceDetailsResponse> searchReSourceDetailss = products.stream().map(temp -> {
                    SearchReSourceDetailsResponse searchReSourceDetails = new SearchReSourceDetailsResponse();
                    BeanUtils.copyProperties(temp, searchReSourceDetails);
                    searchReSourceDetails.setPurchaseInquiryId(temp.getPurchaseInquiryId());
                    return searchReSourceDetails;
                }).collect(Collectors.toList());
                Map<Long, List<SearchReSourceDetailsResponse>> productMap = searchReSourceDetailss.stream().collect(Collectors.groupingBy(SearchReSourceDetailsResponse::getPurchaseInquiryId));
                purchaseList = purchaseList.stream().sorted(Comparator.comparing(SearchReSourceListResponse::getCreateTime).reversed()).collect(Collectors.toList());
                responses = CollectionPageUtil.pageList(purchaseList, request.getCurrent() + 1, request.getPageSize());
                responses.forEach(temp -> {
                    temp.setMateriels(productMap.get(temp.getId()));
                });
            }
        }

        //排序信用积分
        if (request.getOrderType() != null) {
            if (request.getOrderType().equals(OrderTypeEnum.CREATE_TIME_ASC.getCode())) {
                responses = responses.stream().sorted(Comparator.comparing(SearchReSourceListResponse::getCreateTime)).collect(Collectors.toList());
            }
            if (request.getOrderType().equals(OrderTypeEnum.CREATE_TIME_DESC.getCode())) {
                responses = responses.stream().sorted(Comparator.comparing(SearchReSourceListResponse::getCreateTime).reversed()).collect(Collectors.toList());
            }
            if (request.getOrderType().equals(OrderTypeEnum.INTEGRAL_ASC.getCode())) {
                responses = responses.stream().sorted(Comparator.comparing(SearchReSourceListResponse::getMemberIntegral)).collect(Collectors.toList());
            }
            if (request.getOrderType().equals(OrderTypeEnum.INTEGRAL_DESC.getCode())) {
                responses = responses.stream().sorted(Comparator.comparing(SearchReSourceListResponse::getMemberIntegral).reversed()).collect(Collectors.toList());
            }
        }

        //判断当前用户是否已经报过价 && 判断当前用户是否能够报价
        if (user != null && CollectionUtil.isNotEmpty(responses)) {
            Set<Long> ids = responses.stream().map(SearchReSourceListResponse::getId).collect(Collectors.toSet());
            List<QuotedPrice> list = quotedPriceRepository.findAllByPurchaseInquiryIdInAndCreateMemberIdAndCreateMemberRoleId(
                    ids, user.getMemberId(), user.getMemberRoleId()
            );
            responses.forEach(a -> {
                if (CollectionUtil.isNotEmpty(list) && list.stream().anyMatch(b -> b.getPurchaseInquiryId().equals(a.getId()) && b.getTurn().equals(a.getTurn()))) {
                    a.setIsRegister(CommonConstant.State.STATE_START);
                }
                if (user.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode()) &&
                        !a.getMemberId().equals(user.getMemberId())) {
                    a.setCanRegister(Boolean.TRUE);
                }
            });
        } else if (user == null && CollectionUtil.isNotEmpty(responses)) {
            responses = responses.stream().peek(a -> a.setCanRegister(Boolean.TRUE)).collect(Collectors.toList());
        }

        return Wrapper.success(new PageData<>(totalCount, responses));
    }

    /**
     * 获取采购需求单内部流程状态
     */
    @Override
    public Wrapper<List<BiddingExternalWorkStateEnumResponse>> interiorStatus() {
        List<BiddingExternalWorkStateEnumResponse> collect = Arrays.stream(PurchaseInquiryListInteriorWorkStateEnum.values()).map(temp -> {
            BiddingExternalWorkStateEnumResponse response = new BiddingExternalWorkStateEnumResponse();
            response.setName(temp.getName());
            response.setSatatus(temp.getState());
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }

    /**
     * 获取采购需求单外部流程状态
     */
    @Override
    public Wrapper<List<BiddingExternalWorkStateEnumResponse>> externalStatus() {
        List<BiddingExternalWorkStateEnumResponse> collect = Arrays.stream(PurchaseInquiryListExternalWorkStateEnum.values()).map(temp -> {
            BiddingExternalWorkStateEnumResponse response = new BiddingExternalWorkStateEnumResponse();
            response.setName(temp.getName());
            response.setSatatus(temp.getState());
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }

    /**
     * 商城能力--企业直采--采购门户--询价单详情-接口
     */
    @Override
    public Wrapper<PurchaseInquiryDetailsResponse> searchReSourceDetails(BaseDetailsRequest request, UserLoginCacheDTO user) {
        PurchaseInquiryDetailsResponse response = new PurchaseInquiryDetailsResponse();
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        } else {
            return Wrapper.fail(ResponseCode.PURCHASE_ID_CANNOT_BE_EMPTY);
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setOffer(purchaseInquiry.getOffer());
        response.setTransactionUurls(purchaseInquiry.getTransactionUurls());
        response.setAreas(purchaseInquiry.getAreas().stream().map(v -> {
            CountryAreaResponse countryAreaResponse = new CountryAreaResponse();
            BeanUtils.copyProperties(v, countryAreaResponse);
            return countryAreaResponse;
        }).collect(Collectors.toList()));
        response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(purchaseInquiry.getInteriorState()));
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        //查询采购物料
        List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<PurchaseInquiryProductRequest> productRequests = products.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        response.setMateriels(productRequests);
        //查询需求对接会员列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(purchaseInquiry.getType())) {
            response.setDemandMembers(getDemandMembers(purchaseInquiry.getId()));
        }
        response.setShopIds(purchaseInquiry.getShopIds());
        //查询内部操作记录
        response.setInteriorLogs(getInteriorLog(purchaseInquiry.getId()));
        //查询内部流转状态
        response.setInteriorLogStates(getLogStateInterior(purchaseInquiry.getMemberId(), ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), purchaseInquiry.getInteriorNextStep()));
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), roles, purchaseInquiry.getCreateMemberRoleId()));
        //组装截止时间给前端
        response.setDays(0 <= DateUtil.judgeTime(response.getOfferEndTime())[0] ? DateUtil.judgeTime(response.getOfferEndTime())[0] : 0);
        response.setHours(0 <= DateUtil.judgeTime(response.getOfferEndTime())[1] ? DateUtil.judgeTime(response.getOfferEndTime())[1] : 0);
        response.setMinutes(0 <= DateUtil.judgeTime(response.getOfferEndTime())[2] ? DateUtil.judgeTime(response.getOfferEndTime())[2] : 0);

        //判断当前用户是否已经报过价
        if (user != null) {
            if (quotedPriceRepository.existsAllByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleIdAndTurn(response.getId(), user.getMemberId(), user.getMemberRoleId(), response.getTurn())) {
                response.setIsRegister(CommonConstant.State.STATE_START);
            }
        }

        return Wrapper.success(response);
    }

    /**
     * 采购询价--内部流转记录--操作日志
     *
     * @param purchaseInquiryId 询价单ID
     * @param startTime         开始时间
     * @param endTime           结束时间
     */
    @Override
    public Page<InteriorPurchaseInquiryLog> getInquiryInteriorRecordList(PageVO pageVO, Long purchaseInquiryId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return interiorPurchaseInquiryLogRepository.findAll(getInquiryInteriorRecordSpecification(purchaseInquiryId, startTime, endTime), page);
    }

    /**
     * 构建查询条件
     */
    private Specification<InteriorPurchaseInquiryLog> getInquiryInteriorRecordSpecification(Long purchaseInquiryId, Long startTime, Long endTime) {
        return (Specification<InteriorPurchaseInquiryLog>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if (purchaseInquiryId != null && purchaseInquiryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("purchaseInquiryId"), purchaseInquiryId));
            }

            if (startTime != null && startTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if (endTime != null && endTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 采购询价--外部流转记录--操作日志
     *
     * @param purchaseInquiryId 询价单ID
     * @param startTime         开始时间
     * @param endTime           结束时间
     */
    @Override
    public Page<ExternalPurchaseInquiryLog> getInquiryExternalRecordList(PageVO pageVO, Long purchaseInquiryId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return externalLogRepository.findAll(getInquiryExternalRecordSpecification(purchaseInquiryId, startTime, endTime), page);
    }

    /**
     * 构建查询条件
     */
    private Specification<ExternalPurchaseInquiryLog> getInquiryExternalRecordSpecification(Long purchaseInquiryId, Long startTime, Long endTime) {
        return (Specification<ExternalPurchaseInquiryLog>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if (purchaseInquiryId != null && purchaseInquiryId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("purchaseInquiryId"), purchaseInquiryId));
            }

            if (startTime != null && startTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if (endTime != null && endTime > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 查询竞价单列表根据查询类型查询
     */
    private Wrapper<PageData<PurchaseListResponse>> queryList(PurchaseListRequest request, Long shopId) {
        List<PurchaseListResponse> responses;
        QPurchaseInquiry qPurchaseInquiry = QPurchaseInquiry.purchaseInquiry;
        QPurchaseInquiryArea qPurchaseInquiryArea = QPurchaseInquiryArea.purchaseInquiryArea;
        QPurchaseInquiryProduct qPurchaseInquiryProduct = QPurchaseInquiryProduct.purchaseInquiryProduct;
        // 定于获取条件
        BooleanBuilder predicates = new BooleanBuilder();
        //    predicates.and(qPurchaseInquiry.shopIds.contains(shopId));
        predicates.and(qPurchaseInquiry.type.eq(PurchaseInquiryConstant.type.PLATFORM));
        if (null != request.getStartTime()) {
            predicates.and(qPurchaseInquiry.createTime.goe(request.getStartTime()));
        }
        if (null != request.getEndTime()) {
            predicates.and(qPurchaseInquiry.createTime.loe(request.getStartTime()));
        }
        if (null != request.getCategory()) {
            predicates.and(qPurchaseInquiryProduct.category.like("%" + request.getCategory() + "%"));
        }
        if (OrderConstant.State.START.equals(request.getOverdue())) {
            predicates.and(qPurchaseInquiry.offerEndTime.goe(System.currentTimeMillis()));
        }
        if (!ObjectUtils.isEmpty(request.getArea())) {
            if (StringUtils.hasLength(request.getArea().getAreaCode())) {
                predicates.and(qPurchaseInquiryArea.areaCode.eq(request.getArea().getAreaCode()));
            }
            if (StringUtils.hasLength(request.getArea().getCityCode())) {
                predicates.and(qPurchaseInquiryArea.cityCode.eq(request.getArea().getCityCode()));
            }
            if (StringUtils.hasLength(request.getArea().getProvinceCode())) {
                predicates.and(qPurchaseInquiryArea.provinceCode.eq(request.getArea().getProvinceCode()));
            }
        }
        JPAQuery<PurchaseListResponse> query = queryFactory.select(Projections.bean(PurchaseListResponse.class,
                qPurchaseInquiry.id,
                qPurchaseInquiry.purchaseInquiryNo,
                qPurchaseInquiry.details,
                qPurchaseInquiry.createTime,
                qPurchaseInquiry.shopIds,
                qPurchaseInquiry.areas,
                qPurchaseInquiry.deliveryTime,
                qPurchaseInquiry.offerEndTime,
                qPurchaseInquiry.address,
                qPurchaseInquiry.addressId,
                qPurchaseInquiryProduct.id.as("productId"),
                qPurchaseInquiryProduct.category,
                qPurchaseInquiry.createMemberId.as("memberId"),
                qPurchaseInquiry.createMemberName.as("memberName"),
                qPurchaseInquiry.createMemberRoleId.as("memberRoleId")
        )).from(qPurchaseInquiry)
                .leftJoin(qPurchaseInquiryProduct)
                .on(qPurchaseInquiry.id.eq(qPurchaseInquiryProduct.purchaseInquiryId))
                .leftJoin(qPurchaseInquiryArea)
                .on(qPurchaseInquiry.id.eq(qPurchaseInquiryArea.purchaseInquiryId))
                .where(predicates);
        long totalCount = query.fetchCount();
        responses = query.orderBy(qPurchaseInquiry.createTime.desc())
                .fetch();
        if (!CollectionUtils.isEmpty(responses)) {
            //TODO 查询信用分
        }
        return Wrapper.success(new PageData<>(totalCount, responses));
    }


    /**
     * 记录采购询价单内部操作记录
     */
    public void saveInteriorLog(UserLoginCacheDTO sysUser, String operation, Integer step, Integer state, Long id, String auditOpinion) {
        //记录操作记录
        InteriorPurchaseInquiryLog interiorLog = new InteriorPurchaseInquiryLog();
        interiorLog.setRoleName(sysUser.getUserName());
        interiorLog.setDepartment(sysUser.getUserOrgName());
        interiorLog.setPosition(sysUser.getUserJobTitle());
        interiorLog.setPurchaseInquiryId(id);
        interiorLog.setState(state);
        interiorLog.setStep(step);
        interiorLog.setOperation(operation);
        interiorLog.setAuditOpinion(auditOpinion);
        interiorLog.setCreateTime(System.currentTimeMillis());
        interiorLog.setCreateRoleId(sysUser.getMemberRoleId());
        interiorLog.setCreateMemberId(sysUser.getMemberId());
        interiorPurchaseInquiryLogRepository.saveAndFlush(interiorLog);
    }


    /**
     * 判断需求单状态是否可以修改 true:可以修改 false：不可以修改
     */
    private boolean isUpdate(PurchaseInquiry purchaseInquiry) {
        return PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(purchaseInquiry.getInteriorState()) ||
                PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT1.getState().equals(purchaseInquiry.getInteriorState()) ||
                PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT2.getState().equals(purchaseInquiry.getInteriorState()) ||
                PurchaseInquiryListExternalWorkStateEnum.AUDIT_NOT_REQUIREMENTS.getState().equals(purchaseInquiry.getExternalState());
    }


    /**
     * 判断需求单状态是否可以删除 true:可以 false：不可以
     */
    private boolean isDelete(PurchaseInquiry purchaseInquiry) {
        return !PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(purchaseInquiry.getInteriorState()) &&
                !PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT1.getState().equals(purchaseInquiry.getInteriorState()) &&
                !PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT2.getState().equals(purchaseInquiry.getInteriorState()) &&
                externalPurchaseInquiryLogRepository.existsAllByPurchaseInquiryId(purchaseInquiry.getId());
    }


    /**
     * 修改需求单详情
     */
    private void updateOrder(PurchaseInquiry purchaseInquiry, PurchaseInquiryUpdateRequest request) {
        purchaseInquiry.setShopIds(request.getShopIds());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        purchaseInquiry.setType(request.getType());
        purchaseInquiry.setTaxes(request.getTaxes());
        purchaseInquiry.setPurchaseType(request.getPurchaseType());
        purchaseInquiry.setPriceContrast(request.getPriceContrast());
        purchaseInquiry.setPaymentType(request.getPaymentType());
        purchaseInquiry.setPackRequire(request.getPackRequire());
        purchaseInquiry.setOtherRequire(request.getOtherRequire());
        purchaseInquiry.setOffer(request.getOffer());
        purchaseInquiry.setOfferEndTime(request.getOfferEndTime());
        purchaseInquiry.setLogistics(request.getLogistics());
        purchaseInquiry.setDetails(request.getDetails());
        purchaseInquiry.setDeliveryTime(request.getDeliveryTime());
        if (CollectionUtils.isEmpty(request.getAreas())) {
            purchaseInquiry.setIsAreas(OrderConstant.State.STOP);
        } else {
            purchaseInquiry.setIsAreas(OrderConstant.State.START);
            purchaseInquiry.setAreas(request.getAreas().stream().map(temp -> {
                CountryArea area = new CountryArea();
                BeanUtils.copyProperties(temp, area);
                return area;
            }).collect(Collectors.toList()));
        }
        purchaseInquiry.setAddress(request.getAddress());
        purchaseInquiry.setAddressId(request.getAddressId());
        purchaseInquiry.setMaterielMode(request.getMaterielMode());
        purchaseInquiry.setTransactionUurls(request.getTransactionUurls());
    }


    public static MultipartFile getMulFileByFile(File file) {
        FileItem fileItem = createFileItem(file.getPath(), file.getName());
        return new CommonsMultipartFile(fileItem);
    }

    public static FileItem createFileItem(String filePath, String fileName) {
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false, fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            log.error("文件类型转换异常", e);
        }
        return item;
    }


    public void getFile(String writeDate, File file) {
        BufferedWriter out = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8);
            out = new BufferedWriter(osw);
            osw.write(writeDate + "\r\n");
            osw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseShopInquiryAddList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        //发布商城类型为企业商城
        request.setShopType(ShopTypeEnum.ENTERPRISE.getCode());
        Wrapper<PageData<PurchaseInquiryListResponse>> query = getQuery(sysUser, request, PurchaseInquiryListEnum.ADD_PURCHASE_INQUIRY_LIST.getType());
        if (ResponseCode.SUCCESS.getCode() == query.getCode() && !CollectionUtils.isEmpty(query.getData().getData())) {
            query.getData().getData().forEach(response -> {
                response.setButton(PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState().equals(response.getInteriorState()) ? ButtonEnum.SUBMIT_ORDER.getStep() : ButtonEnum.CONFIRM_ORDER.getStep());
            });
        }
        return query;
    }
}
